package cn.com.agree.bigdata.vmdatahandle.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.*;

@Slf4j
public class AgreeFileUtil {
    private static final String LINUX_OS_SYSTEM = "linux";

    /**
     * 读取文件内容
     *
     * @param path
     * @return
     */
    public static String readReaderFile(String path) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        FileReader fr = null;
        char[] cbuf = new char[1024];
        int hasReaded;
        try {
            fr = new FileReader(path);
            br = new BufferedReader(fr);

            while ((hasReaded = br.read(cbuf)) > 0) {
                sb.append(cbuf, 0, hasReaded);
            }

        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception ignored) {

                }
            }
            if (fr != null) {
                try {
                    fr.close();
                } catch (Exception ignored) {

                }
            }
        }
        return sb.toString();
    }

    public static String readReaderFile(String path, Charset charset) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader br = null;
        FileInputStream fi = null;
        InputStreamReader inputStreamReader = null;

        char[] cbuf = new char[1024];
        int hasReaded;
        try {
            fi = new FileInputStream(path);
            inputStreamReader = new InputStreamReader(fi, charset);
            br = new BufferedReader(inputStreamReader);

            while ((hasReaded = br.read(cbuf)) > 0) {
                sb.append(cbuf, 0, hasReaded);
            }

        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception ignored) {

                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (Exception ignored) {

                }
            }
            if (fi != null) {
                try {
                    fi.close();
                } catch (Exception ignored) {

                }
            }
        }
        return sb.toString();
    }

    public static List<String> readJsonContentFile(String path, String charsetName, int maxLine) throws Exception {
        BufferedReader br = null;
        FileInputStream fi = null;
        InputStreamReader inputStreamReader = null;
        List<String> contents = new ArrayList<>(4);
        int hasReadLine = 0;

        String line;
        try {
            fi = new FileInputStream(path);
            inputStreamReader = new InputStreamReader(fi, charsetName);
            br = new BufferedReader(inputStreamReader);

            while ((line = br.readLine()) != null && hasReadLine <= maxLine) {
                contents.add(line);
            }
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception ignored) {

                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (Exception ignored) {

                }
            }
            if (fi != null) {
                try {
                    fi.close();
                } catch (Exception ignored) {

                }
            }
        }
        return contents;
    }

    /**
     * 把整块内容写入文件
     *
     * @param filePath
     * @param content
     */
    public static void writeFile(String filePath, byte[] content) throws IOException {
        FileOutputStream fio = null;
        BufferedOutputStream bos = null;

        try {
            fio = new FileOutputStream(filePath);
            bos = new BufferedOutputStream(fio);
            bos.write(content);
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (Exception ignore) {
                }
            }
            if (fio != null) {
                try {
                    fio.close();
                } catch (Exception ignore) {

                }
            }
        }
    }

    public static void writeFile(String filePath, String str) throws IOException {
        FileOutputStream fio = null;
        BufferedOutputStream bos = null;

        try {
            fio = new FileOutputStream(filePath);
            bos = new BufferedOutputStream(fio);
            byte[] content;
            try {
                content = str.getBytes(StandardCharsets.UTF_8);
            } catch (Exception e) {
                try {
                    content = str.getBytes("gbk");
                } catch (Exception ein) {
                    content = str.getBytes();
                }
            }
            bos.write(content);
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (Exception ignore) {
                }
            }
            if (fio != null) {
                try {
                    fio.close();
                } catch (Exception ignore) {

                }
            }
        }
    }

    public static void writeFile(String filePath, String str, Charset charset) throws IOException {
        FileOutputStream fio = null;
        BufferedOutputStream bos = null;

        try {
            fio = new FileOutputStream(filePath);
            bos = new BufferedOutputStream(fio);
            byte[] content;
            try {
                content = str.getBytes(charset);
            } catch (Exception e) {
                content = str.getBytes();
            }
            bos.write(content);
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (Exception ignore) {
                }
            }
            if (fio != null) {
                try {
                    fio.close();
                } catch (Exception ignore) {

                }
            }
        }
    }

    public static void writeReadOnlyFile(String filePath, String str) throws Exception {
        FileOutputStream fio = null;
        BufferedOutputStream bos = null;

        try {
            File file = new File(filePath);
            fio = new FileOutputStream(file);
            bos = new BufferedOutputStream(fio);
            byte[] content;
            try {
                content = str.getBytes(StandardCharsets.UTF_8);
            } catch (Exception e) {
                try {
                    content = str.getBytes("gbk");
                } catch (Exception ein) {
                    content = str.getBytes();
                }
            }
            bos.write(content);
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (Exception ignore) {
                }
            }
            if (fio != null) {
                try {
                    fio.close();
                } catch (Exception ignore) {

                }
            }
        }
        File file = new File(filePath);
        boolean ok = file.setReadOnly();
        if (ok) {
            log.info("文件{}设置只读成功", filePath);
        } else {
            String msg = String.format("文件%s设置只读失败", filePath);
            throw new Exception(msg);
        }
    }


    public static void writeFile(String filePath, String str, boolean ownerReadWrite) throws Exception {
        FileOutputStream fio = null;
        BufferedOutputStream bos = null;

        try {
            File file = new File(filePath);
            fio = new FileOutputStream(file);
            bos = new BufferedOutputStream(fio);
            byte[] content;
            try {
                content = str.getBytes(StandardCharsets.UTF_8);
            } catch (Exception e) {
                try {
                    content = str.getBytes("gbk");
                } catch (Exception ein) {
                    content = str.getBytes();
                }
            }
            bos.write(content);
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (Exception ignore) {
                }
            }
            if (fio != null) {
                try {
                    fio.close();
                } catch (Exception ignore) {

                }
            }
        }
        if (ownerReadWrite) {
            String osName = System.getProperty("os.name").toLowerCase(Locale.ROOT);
            if (osName.startsWith(LINUX_OS_SYSTEM)) {
                Set<PosixFilePermission> perms = new HashSet<>();
                perms.add(PosixFilePermission.OWNER_READ);
                perms.add(PosixFilePermission.OWNER_WRITE);
                perms.add(PosixFilePermission.GROUP_READ);
                perms.add(PosixFilePermission.OTHERS_READ);
                Path path = Paths.get(filePath);
                Files.setPosixFilePermissions(path, perms);
            }
        }
    }
}


